package com.bhh.aio;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.channels.ServerSocketChannel;

/**
 * @author bhh
 * @description 演示 异步IO模型下的 Server与Client
 * @date Created in 2021-04-14 15:35
 * @modified By
 */
@Slf4j
public class Server {
    private static final int PORT = 8888;

    private AsynchronousServerSocketChannel server;

    public void start(){
        try {
            server = AsynchronousServerSocketChannel.open();
            server.bind(new InetSocketAddress(PORT));
            while (true) {
                server.accept(null, new AcceptHandler());
                System.in.read();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 继承接口CompletionHandler
     * CompletionHandler<AsynchronousSocketChannel, Object>
     *     泛型1 : 调用该对象的方法的返回值, 例如第29行accept()的返回值
     *     泛型2 : attachment(附件)类型, 例如第29行accept()的第一个参数
     *
     */
    private class AcceptHandler implements
            CompletionHandler<AsynchronousSocketChannel, Object> {
        /**
         * 异步调用完成后运行
         * @param result
         * @param attachment
         */
        @Override
        public void completed(AsynchronousSocketChannel result, Object attachment) {

        }

        /**
         * 异步调用失败后运行
         * @param exc
         * @param attachment
         */
        @Override
        public void failed(Throwable exc, Object attachment) {

        }
    }
}
